package com.liuguang.framework.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JSONUtil {
    private static Gson gson = new GsonBuilder().create();

    public static <T> T parseJSON(String str, Class<T> cls) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return gson.fromJson(str, cls);
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static <T> T parseJSON(String str, Type type) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return gson.fromJson(str, type);
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static String toJSON(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return gson.toJson(obj);
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static <T> T mapToBean(Map<String, Object> map, Class<T> cls) {
        if (map == null) {
            return null;
        }
        try {
            return parseJSON(toJSON(map), cls);
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static Map<String, String> BeanToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return (Map) gson.fromJson(toJSON(obj), new TypeToken<Map<String, String>>() {
            }.getType());
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static List<Map<String, String>> BeanToList(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return (List) gson.fromJson(toJSON(obj), new TypeToken<List<Map<String, String>>>() {
            }.getType());
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }

    public static <T> List<T> ListToBean(List<Map<String, Object>> list, Class<T> cls) {
        if (list == null) {
            return null;
        }
        try {
            ArrayList arrayList = new ArrayList();
            for (Map mapToBean : list) {
                arrayList.add(mapToBean(mapToBean, cls));
            }
            return arrayList;
        } catch (Exception e) {
            ToastUtils.show(e.getMessage());
            return null;
        }
    }
}
